import {Inject} from 'plugins'
import config from 'config';

@Inject('$scope', '$state', 'ui.dialog', 'ui.http', 'ui.api', 'DepartService')
export class Depart {
	constructor($scope, $state, dialog, http, api, service) {
		var dataSource = api.tree({
			scope: $scope,
			type: 'tree',
			url: 'basic/branch/treeBranch'
		});
		dataSource.bind('requestEnd', function() {
			var tree = $scope.tree;
			setTimeout(function() {
				var root = dataSource.at(0);
				var el = tree.findByUid(root.uid);
				tree.select(el);
			}, 0);
		});
		// $scope.$on("kendoWidgetCreated", function(event, widget) {
		// 	var tree = $scope.tree;
		// 	if (widget === tree) {
		// 		var dataSource = tree.dataSource;
		// 		setTimeout(function() {
		// 			var root = dataSource.at(0);
		// 			var el = tree.findByUid(root.uid);
		// 			tree.select(el);
		// 		}, 0);
		// 	}
		// });

		$scope.treeQuery = function() {

		}

		$scope.treeReload = function() {
			api.treeReload.apply($scope, arguments);
		}

		var getTreeNode = $scope.getTreeNode = function() {
			return $scope.selectedTreeNode;
		}

		$scope.hasNodeSelected = function() {
			var node = getTreeNode();
			return node != null;
		}
		$scope.isNodeRoot = function() {
			var node = getTreeNode(),
				root;
			return !node || !(root = $scope.tree.dataSource.at(0)) || root.id == node.id;
		}

	    var data = $state.current.data || {};
	    var tabs = $scope.tabs = data.tabs;

	    $scope.welcome = data.welcome;

		$scope.activeIndex = 0;

		var changeState = $scope.changeState = function(state) {
			state = state || $state.current.name;
			for (var i = 0, l = tabs.length; i < l; i++) {
				var tab = tabs[i];
				if (tab.state == state) {
					$scope.activeIndex = i;
					break;
				}
			}
		}

		var states = tabs.map(function(tab, index) {
			if (tab.active) {
				$scope.activeIndex = index;
			}
			return tab.state;
		});

		$scope.add = service.add;
		$scope.edit = service.edit;
		$scope.remove = service.remove;

		$scope.select = function(state) {
			if (state) {
				if ($state.is(state)) {
					$state.reload(state);
				} else {
					$state.go(state);
				}
			} else {
				state = $state.current.name;
				if (!state || states.indexOf(state) === -1) {
					$state.go(states[$scope.activeIndex]);
				} else {
					$scope.select(state);
				}
			}
		}

		$scope.changeNode = function(node) {
			$scope.selectedTreeNode = node;

			if ($scope.isNodeRoot()) {
				$scope.select('depart.list');
			} else {
				$scope.select();
			}
		}
	}
}